<?php

  
    preg_match('/^(www\.|)(([^\.]+)\..*)$/', $_SERVER['HTTP_HOST'], $matches);
    define ('HOST', $matches[2]);
  
  
    # Runtime path constants definition
    define ('S', DIRECTORY_SEPARATOR);
    define ('ROOT_DIR', str_replace(S . S, S, realpath(dirname(__FILE__))) . S);
    define ('ENGINE_DIR', ROOT_DIR . 'engine' . S);
    define ('RUNTIME_DIR', ENGINE_DIR . 'runtime' . S);
    define ('MODEL_DIR', ENGINE_DIR . 'model' . S);
    define ('LIBS_DIR', ENGINE_DIR . 'libs' . S);
    define ('CONFIG_DIR', ROOT_DIR. 'config' . S);
    define ('PUBLIC_DIR', ROOT_DIR . 'public' . S);
    define ('COMPILED_PHP_DIR', ROOT_DIR . 'tmp' . S . 'compiled_php' . S);


    # Core non-class functions
    require(MODEL_DIR . 'core-functions.php');


    # Core models
    require_once(MODEL_DIR . 'Akrudo.php');
    require_once(MODEL_DIR . 'Nails.php');
    require_once(MODEL_DIR . 'Error.php');
    require_once(MODEL_DIR . 'ActiveRecord.php');
    require_once(MODEL_DIR . 'AppController.php');
    require_once(MODEL_DIR . 'ActiveCollection.php');
    require_once(MODEL_DIR . 'ActiveRecordCollection.php');
    require_once(MODEL_DIR . 'Column.php');
    require_once(MODEL_DIR . 'Association.php');
    require_once(MODEL_DIR . 'SPYC.php');
    require_once(MODEL_DIR . 'File.php');
    require_once(MODEL_DIR . 'FileHandler.php');
    require_once(MODEL_DIR . 'Inflector.php');
    require_once(MODEL_DIR . 'Result.php');
    require_once(MODEL_DIR . 'PreCompiler.php');
    //require_once(MODEL_DIR . 'ScaffoldedController.php');
    require_once(MODEL_DIR . 'AppViewer.php');
    require_once(MODEL_DIR . 'Dir.php');
    //require_once(MODEL_DIR . 'Common.php');
    //require_once(MODEL_DIR . 'JS.php');
    //require_once(MODEL_DIR . 'Timer.php');
    //require_once(MODEL_DIR . 'Logger.php');
    
    
    # Akrudo data types
    require_once(MODEL_DIR . 'Date.php');



    # PEAR model
    //require_once "Auth.php";
    require_once "Log.php";
    require_once "MDB2.php";



    # Additional libraries / helpers | non model ones
    require_once(LIBS_DIR . 'helpers' . S . '_helpers.php');


    
    # AR constants definitions
    define('first', 'first');
    define('last', 'last');
    define('all', 'all');

  
  
  
  
  
  
  
  
  
  

  # Nails construct
  $akrudo = new Akrudo();
  $GLOBALS['Akrudo'] =& $akrudo;
  
### Loggers
  # Loading YAML config file into $akrudo 
  $akrudo->load_config_file('logger');
  $logger = &Log::singleton('composite');
  
  
  ### Console log
    $console_conf = array('lineFormat' => '  %4$s');
    $console_log = &Log::singleton('console', '', '', $console_conf);
    $console_log->setMask(127);
    
    # Adding logger to parent composite logger
    $logger->addChild($console_log);
    
    # Creating mask from configuration variable
    //$levels = array_keys(array_intersect($akrudo->config->logger['console'], array(1)));
    //$levels = array_map (array('Akrudo', 'get_error_code'), $levels);
    //$levels = array_map (array('Log', 'MASK'), $levels);
    //$console_log->setMask(array_sum($levels));
  
  
  #$$ Assigning loggers as Akrudo variable
    $akrudo->logger =& $logger;
  
  
  
  
  
  
  
  
### Setting DB options
  
  # Loading YAML config file
  $akrudo->load_config_file('db');
  
  ### DSN set up
    # Going thourgh all of db parameter sets
    foreach ($akrudo->config->db as $environment => $params) {
      
      # Defining '$environment_DSN' constant for each params set
      define(trim($environment) . '_DSN', $params['driver'] . '://' . $params['username'] . ':' . $params['password'] . '@' . $params['hostname'] . '/' . $params['database']);
    }
  
  

  # Throwing an error if env not specified

  if (!isset($argv[1])) {

    Akrudo::raise_err("Please specify environment variable.");
    Akrudo::raise_err("Type 'help' for help...");
    

  }

  

  # Checking if inputted env is specified in config file

  $env = $argv[1];
  define ('ENV', $env);

  if (!in_array($env, array_keys($akrudo->config->db))) {

    Akrudo::raise_err("No '{$env}' env specified in config file.");

  }

  
  Akrudo::raise_info("");
  Akrudo::raise_info("Raking '{$env}' enviroment...");

  

  # Checking if specified $env is one of two special prod-like envs

  if (in_array($env, array('test', 'productioon'))) {

    

    # PreCompiling APP files (model, controller, views...)

    $model_dir = ROOT_DIR . 'app' . S . 'model' . S;

    $models = FileHandler::list_folder_files($model_dir);

    $compiled_dir = ROOT_DIR . $env . S;

    Akrudo::raise_info("");
    Akrudo::raise_info("Models:");

    # Looping through created models

    foreach ($models as $model) {

      $class_name = $model->filename;

      $add = ActiveRecord::load_class($model_dir, $class_name, false, true);

      $path = 'app' . S . 'model' . S . $model->basename;

      $path = str_replace(ROOT_DIR, '', $model->path);


      PreCompiler::compile_file($path, ROOT_DIR, $compiled_dir);

      PreCompiler::add_to_class($compiled_dir . $path, $add);
      Akrudo::raise_info("  compile  {$path}... OK");

    }

    

    ############################################################

    

    # PreCompiling APP files (model, controller, views...)

    $controller_dir = ROOT_DIR . 'app' . S . 'controller' . S;

    $controllers = FileHandler::list_folder_files($controller_dir);

    

    Akrudo::raise_info("");
    Akrudo::raise_info("Controllers:");

    # Looping through created models

    foreach ($controllers as $controller) {

      $path = 'app' . S . 'controller' . S . $controller->basename;

      $path = str_replace(ROOT_DIR, '', $controller->path);


      PreCompiler::compile_file($path, ROOT_DIR, $compiled_dir);

      $method_name = 'render';

      $add = "  function {$method_name}() {\n      \$args = func_get_args();return parent::parent_{$method_name}('{$model->filename}', 1, \$args[0]);\n    }\n\n  ";

      PreCompiler::add_to_class($compiled_dir . $path, $add);

      Akrudo::raise_info("  compile  {$path}... OK");

    }

    

    ############################################################

    

    # PreCompiling APP files (model, controller, views...)

    $view_dir = ROOT_DIR . 'app' . S . 'view' . S;

    $view_folders = FileHandler::list_folder_directories($view_dir);

    Akrudo::raise_info("");
    Akrudo::raise_info("Views:");

    # Looping through created models

    PreCompiler::compile_folder('app' . S . 'view', ROOT_DIR, $compiled_dir);

  }
  
  
    Akrudo::raise_info("");
    Akrudo::raise_info("Configs:");
  
    $path = 'config' . S . 'routes.php';
    PreCompiler::compile_file($path, ROOT_DIR, $compiled_dir);
    Akrudo::raise_info("  compile  {$path}... OK");

  

  

  FileHandler::ForcedCreateFile(CONFIG_DIR . 'basic.yaml', "environment: {$env}\ncompile_php: false");

  

  

  Akrudo::raise_info("");
  Akrudo::raise_info("Rake complete!");

  

  

?>